import express from 'express';
import * as comments from '../../controllers/comments.js';
// 引入JWT验证中间件
import { auth } from '../../auth/auth.js';
const router = express.Router();

// 19. 评论搜索
router.get('/search', auth(), async (req, res, next) => {
  try {
    console.log('开始处理 /admin/comment/search 请求...');
    const { page = 1, perpage = 6 } = req.query;
    // 获取所有评论
    let data = await comments.selectAllComments(parseInt(page), parseInt(perpage));
    let countResult = await comments.selectCommentsCount();
    let [{ count }] = countResult;
    let pages = Math.ceil(count / parseInt(perpage));
    res.send({
      code: 200,
      msg: "获取成功",
      pages,
      page: parseInt(page),
      data: data.map(item => ({
        id: item.id,
        avatar: item.avatar || "/uploads/default-avatar.jpg",
        name: item.name,
        content: item.content,
        state: item.state || "待审核",
        articleId: item.articleId,
        articleTitle: item.articleTitle || "未知文章",
        date: item.date
      }))
    });
  } catch (error) {
    console.error('评论搜索失败:', error);
    res.status(500).send({
      code: 500,
      msg: "获取失败"
    });
  }
});

// 20. 评论审核-通过
router.post('/pass', auth(), async (req, res, next) => {
  try {
    console.log('开始处理 /admin/comment/pass 请求...');
    const { id } = req.body;
    // console.info('请求体数据:', req.body, id);
    if (!id) {
      return res.status(400).send({
        code: 400,
        msg: "评论ID不能为空"
      });
    }
    await comments.updateCommentState(id, "已通过");
    res.send({
      code: 200,
      msg: "设置成功"
    });
  } catch (error) {
    console.error(error);
    res.status(500).send({
      code: 500,
      msg: "设置失败"
    });
  }
});

// 21. 评论审核-拒绝
router.post('/reject', auth(), async (req, res, next) => {
  try {
    console.log('开始处理 /admin/comment/reject 请求...');
    // console.log('请求体数据:', req.body); 
    const { id } = req.body;
    if (!id) {
      return res.status(400).send({
        code: 400,
        msg: "评论ID不能为空"
      });
    }
    await comments.updateCommentState(id, "已拒绝");
    res.send({
      code: 200,
      msg: "设置成功"
    });
  } catch (error) {
    console.error(error);
    res.status(500).send({
      code: 500,
      msg: "设置失败"
    });
  }
});

// 22. 删除评论
router.post('/delete', auth(), async (req, res, next) => {
  try {
    console.log('开始处理 /admin/comment/delete 请求...');
    // console.log('请求体数据:', req.body);
    const { id } = req.body;
    if (!id) {
      return res.status(400).send({
        code: 400,
        msg: "评论ID不能为空"
      });
    }
    await comments.deleteComment(id);
    res.send({
      code: 200,
      msg: "删除成功"
    });
  } catch (error) {
    console.error('删除评论失败:', error);
    res.status(500).send({
      code: 500,
      msg: "删除失败"
    });
  }
});

export default router;
